from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from time import sleep

# 初始化浏览器（指定驱动路径）
service = Service(executable_path="E:\\python\\python38\\chromedriver.exe")
driver = webdriver.Chrome(service=service)
driver.get("https://demo6.tp-shop.cn/")
sleep(2)  # 页面暂停
driver.maximize_window()
sleep(2)
wait = WebDriverWait(driver, 15)  # 定义 wait 对象

try:
    driver.get("https://demo6.tp-shop.cn/Home/Index/index.html")
    sleep(2)
    driver.maximize_window()

    # 注入 cookie
    cookies = [
        {'name': 'PHPSESSID', 'value': 'j04ld1rrp7it8to9ccu3aahuc5'},
        {'name': 'user_id', 'value': '320'},
        {'name': 'uname', 'value': '13088888888%40qq.com'}
    ]

    for cookie in cookies:
        try:
            driver.add_cookie(cookie)
        except Exception as e:
            print(f"添加 Cookie 失败: {cookie['name']}, 错误: {e}")

    driver.refresh()
    sleep(3)

    # 搜索小米
    driver.find_element(By.CSS_SELECTOR, "#q").send_keys("小米")
    driver.find_element(By.CSS_SELECTOR, ".ecsc-search-button").click()
    sleep(2)

    # 点击第一个商品
    driver.find_element(By.CSS_SELECTOR, ".lazy-list").click()
    sleep(2)

    # 切换到商品详情页（如果打开新窗口）
    if len(driver.window_handles) > 1:
        driver.switch_to.window(driver.window_handles[-1])

    # 加入购物车
    driver.find_element(By.LINK_TEXT, "加入购物车").click()
    sleep(2)

    # 切换到弹窗 iframe 并点击“去购物车结算”
    print("等待弹窗 iframe...")
    iframe = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, ".layui-layer-iframe iframe")))
    driver.switch_to.frame(iframe)

    checkout_btn = wait.until(EC.element_to_be_clickable((By.XPATH, "//a[text()='去购物车结算']")))
    checkout_btn.click()
    print("已点击去购物车结算！")

    # 切回主页面
    driver.switch_to.default_content()

    # ⚠️ 关键：等待前一个弹窗的遮罩层完全消失
    print("等待遮罩层消失...")
    wait.until(EC.invisibility_of_element_located((By.CLASS_NAME, "layui-layer-shade")))

    # 点击“去结算”（在订单确认页）
    print("等待去结算按钮...")
    pay_btn = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".paytotal")))
    pay_btn.click()
    print("已点击去结算！")

    # 检查是否有遮罩
    shades = driver.find_elements(By.CLASS_NAME, "layui-layer-shade")
    if shades:
        print("❌ 仍有遮罩层！数量:", len(shades))
        driver.save_screenshot("error_shade.png")
    # 点击新增地址
    print("点击新增地址...")
    diz = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#addNewAddress")))
    diz.click()
    sleep(2)

    # 切换到地址填写 iframe
    print("等待地址弹窗 iframe...")
    address_iframe = wait.until(
        EC.presence_of_element_located((By.CSS_SELECTOR, ".layui-layer-iframe iframe"))
    )
    driver.switch_to.frame(address_iframe)

    # 填写地址
    wait.until(EC.presence_of_element_located((By.ID, "province")))

    driver.find_element(By.NAME, "consignee").clear()
    driver.find_element(By.NAME, "consignee").send_keys("阿奇星")

    driver.find_element(By.NAME, "zipcode").clear()
    driver.find_element(By.NAME, "zipcode").send_keys("530612")

    driver.find_element(By.NAME, "mobile").clear()
    driver.find_element(By.NAME, "mobile").send_keys("13088888888")

    driver.find_element(By.ID, "address").clear()
    driver.find_element(By.ID, "address").send_keys("马山黑山羊肉")

    # 1. 选择省份
    province_select = Select(driver.find_element(By.ID, "province"))
    province_select.select_by_visible_text("广西壮族自治区")

    # 2. 等待城市下拉框中出现"南宁市"
    print("等待城市选项加载...")
    wait.until(
        EC.text_to_be_present_in_element((By.ID, "city"), "南宁市")
    )
    # 或者更稳妥：等待 option 出现
    wait.until(
        EC.presence_of_element_located((By.XPATH, "//select[@id='city']/option[text()='南宁市']"))
    )

    # 3. 选择城市
    city_select = Select(driver.find_element(By.ID, "city"))
    city_select.select_by_visible_text("南宁市")

    # 4. 等待区县加载
    wait.until(
        EC.presence_of_element_located((By.XPATH, "//select[@id='district']/option[text()='兴宁区']"))
    )
    district_select = Select(driver.find_element(By.ID, "district"))
    district_select.select_by_visible_text("兴宁区")

    # 5. 等待街道加载（如果需要）
    try:
        wait.until(
            EC.presence_of_element_located((By.XPATH, "//select[@id='twon']/option[text()='民生街道']"))
        )
        twon_select = Select(driver.find_element(By.ID, "twon"))
        twon_select.select_by_visible_text("民生街道")
    except:
        print("街道选项未加载或不存在，跳过")

    # 点击保存
    save_btn = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".box-ok.ma-le--70")))
    save_btn.click()

    # 切回主页面
    driver.switch_to.default_content()
    print("✅ 地址保存完成，已返回主页面")

    # 提交订单
    print("提交订单...")
    submit_btn = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#submit_order")))
    submit_btn.click()
    print("✅ 订单已提交！")

finally:
    # driver.quit()
    pass

